<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-header">
        <img src="../../public/robot-icon.svg" alt="AI应用中心 Logo" class="logo" />
        <h2>邮箱认证</h2>
      </div>

      <div class="form-container">
        <p class="login-tip">请使用QQ邮箱完成认证</p>
        
        <el-form @submit.prevent="handleEmailAuth" label-position="top">
          <el-form-item label="">
            <el-input v-model="email" placeholder="请输入QQ邮箱">
              <template #prefix>
                <el-icon class="el-input__icon"><Message /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="">
            <div class="verification-code-input">
              <el-input v-model="verificationCode" placeholder="请输入验证码">
                <template #prefix>
                  <el-icon class="el-input__icon"><Key /></el-icon>
                </template>
              </el-input>
              <el-button :disabled="isSendingCode || !email" @click="sendCode">{{ codeButtonText }}</el-button>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" native-type="submit" class="login-button" :disabled="!email || !verificationCode">
              完成认证
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {onUnmounted, ref} from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Message, Key } from '@element-plus/icons-vue';
import { emailCodeAPI } from "../api/code/code.js";
import {emailAuthAPI} from "../api/login/login.js";

const router = useRouter();
const email = ref('');
const verificationCode = ref('');
const isSendingCode = ref(false);
const codeButtonText = ref('发送验证码');
let codeTimer = null;

const sendCode = async () => {
  if (!email.value) {
    ElMessage.warning('请输入QQ邮箱！');
    return;
  }
  if (!isEmailRight(email.value)) {
    ElMessage.warning('请输入正确的QQ邮箱！');
    return;
  }

  try {
    const res = await emailCodeAPI(email.value);
    if (res.code === 200) {
      ElMessage.success(`验证码已发送到 ${email.value}`);
      isSendingCode.value = true;
      let seconds = 60;
      codeButtonText.value = `重新发送 (${seconds}s)`;
      codeTimer = setInterval(() => {
        seconds--;
        if (seconds > 0) {
          codeButtonText.value = `重新发送 (${seconds}s)`;
        } else {
          isSendingCode.value = false;
          codeButtonText.value = '发送验证码';
          clearInterval(codeTimer);
          codeTimer = null;
        }
      }, 1000);
    }
  } catch (error) {
    ElMessage.error('发送验证码失败，请重试');
  }
};

const handleEmailAuth = async () => {
  if (!email.value || !verificationCode.value) {
    ElMessage.warning('请输入邮箱和验证码！');
    return;
  }
  if (!isEmailRight(email.value)) {
    ElMessage.warning('请输入正确的QQ邮箱！');
    return;
  }

  try {
    // TODO: 调用邮箱认证接口
    const res = await emailAuthAPI({
      email: email.value,
      code: verificationCode.value,
      uuid: localStorage.getItem('ai_love_uuid')
    });
    if (202 === res.code){
      ElMessage.success('登录成功！');
      if (res.data.userAccount){//登录成功
        router.push({ name: 'FirstLoginSetup', params: { userAccount: res.data.userAccount} }); // 跳转到首次登录设置页面
      }else {//跳转到继续密码认证
        router.push('/home')
      }
    }
  } catch (error) {
    ElMessage.error('认证失败，请重试');
  }
};

const isEmailRight = (value) => {
  if (value == null || value.trim() === '') {
    return false;
  }
  return /^[a-zA-Z0-9_-]+@qq\.com$/.test(value);
};

// 清理定时器
onUnmounted(() => {
  if (codeTimer) {
    clearInterval(codeTimer);
  }
});
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #1a1a2e;
  padding: 20px;
}

.login-card {
  width: 400px;
  max-width: 95%;
  padding: 40px;
  border-radius: 12px;
  background-color: #2a2a40;
  color: #ffffff;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.6);
  border: 1px solid #404060;
}

.login-header {
  margin-bottom: 30px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-header img {
  height: 50px;
  margin-right: 10px;
}

.login-header h2 {
  color: #66b1ff;
  font-size: 1.8em;
  text-shadow: 0 0 8px #66b1ff;
}

.form-container {
  width: 100%;
}

.login-tip {
  text-align: center;
  color: #b3b3b3;
  font-size: 0.9em;
  margin-bottom: 20px;
}

.verification-code-input {
  display: flex;
  gap: 10px;
  align-items: center;
}

.verification-code-input .el-input {
  flex: 1;
}

.el-button.login-button {
  width: 100%;
  margin-top: 10px;
  font-size: 1.1em;
  padding: 12px 20px;
  border-radius: 4px;
}

@media (max-width: 768px) {
  .login-card {
    width: 98%;
    padding: 30px 20px;
  }

  .login-header {
    margin-bottom: 20px;
  }

  .login-header img {
    height: 40px;
  }

  .login-header h2 {
    font-size: 1.6em;
  }

  .login-tip {
    font-size: 0.8em;
    margin-bottom: 15px;
  }

  .el-button.login-button {
    font-size: 1em;
    padding: 10px 15px;
  }
}
</style> 